package com.Matching;

import android.util.Log;

import java.util.Vector;

/**
 * Created by Cyc on 2016/9/7 0007.
 */
public class MatchingRoundness {
    private String thisLogTag = "MatchingRoundness";

    double centerX = 0;
    double centerY = 0;
    double radius = 0;

   public boolean leastSquareMethod(Vector<double[]> point) {
       int num = point.size();
       double x,y;
       double x1,x2,x3,y1,y2,y3,x1y1,x2y1,x1y2;
       double C, D, E, G, H, N;
       double a, b, c;

       x1 = x2 = x3 = y1 = y2 = y3 = x1y1 = x2y1 = x1y2 =0;

       if (num < 3)
           return false;

       for(int i = 0; i < num; i++) {
           x = point.get(i)[0];
           y = point.get(i)[1];
           x1 += x;
           y1 += y;
           x2 += x * x;
           y2 += y * y;
           x3 += x * x * x;
           y3 += y * y * y;
           x1y1 += x * y;
           x1y2 += x * y * y;
           x2y1 += x * x * y;
       }

       N = num;
       C = N * x2 - x1 * x1;
       D = N * x1y1 - x1 * y1;
       E = N * x3 + N * x1y2 - (x2 + y2) * x1;
       G = N * y2 - y1 * y1;
       H = N * x2y1 + N * y3 - (x2 + y2) * y1;

       a = (H * D - E * G) / (C * G - D * D);
       b = (H * C - E * D) / (D * D - G * C);
       c = -(a * x1 + b * y1 + x2 + y2)/N;

       centerX = a / (-2.0);
       centerY = b / (-2.0);
       radius = Math.sqrt(a * a + b * b - 4 * c) / 2.0;

       Log.i(thisLogTag, String.format("x: %.3f  y: %.3f  R: %.3f", centerX, centerY, radius));
       return true;
   }
}
